// Modules to control application life and create native browser window
const {app, BrowserWindow ,ipcMain } = require('electron')
const path = require('path')

// Keep a global reference of the window object, if you don't, the window will
// be closed automatically when the JavaScript object is garbage collected.

let mainWindow

function createWindow () {
    // 引入menu
    const {Menu, dialog} = require('electron')
  // Create the browser window.
  mainWindow = new BrowserWindow({
      fullscreen: false,
      alwaysOnTop: false,
      frame: true,
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js')
    }
  })
    // 创建菜单栏
    const menu = Menu.buildFromTemplate([
        {
            label: '菜单',
            submenu: [
                {
                    id: 0,
                    label: '打开文件',
                    click() {
                        // 选择文件
                        dialog.showOpenDialog({
                                title: '选择文件',
                                properties: ['openFile'],
                                filters: [
                                    {name: 'html', extensions: ['html']}
                                ]
                            },
                            function (filePaths) {
                                // 加载html
                                mainWindow.loadURL(url.format({
                                    //pathname: path.join(__dirname, 'index.html'),
                                    pathname: filePaths[0],
                                    protocol: 'file:',
                                    slashes: true
                                }))
                            }
                        )
                    }
                },
                {
                    id: 1,
                    label: '开发者工具',
                    click() {
                        // 打开开发者工具。
                        mainWindow.webContents.openDevTools()
                    }
                },
                {
                    id: 2,
                    label: '退出',
                    role: 'quit'
                }
            ]
        },{ label: '文件',
            submenu:[
                { //menu.items获取是的主菜单一级菜单的菜单数组，menu.items[0]在这里就是第1个File菜单对象，在其子菜单submenu中添加新的子菜单
                    label: "新建",
                    click(){
                        mainWindow.webContents.send('action', 'new'); //点击后向主页渲染进程发送“新建文件”的命令
                    },
                    accelerator: 'CmdOrCtrl+N' //快捷键：Ctrl+N
                },
                {
                    label: "打开",
                    click(){
                        mainWindow.webContents.send('action', 'open'); //点击后向主页渲染进程发送“打开文件”的命令
                    },
                    accelerator: 'CmdOrCtrl+O' //快捷键：Ctrl+O
                },
                {
                    label: "保存",
                    click(){
                        mainWindow.webContents.send('action', 'save'); //点击后向主页渲染进程发送“保存文件”的命令
                    },
                    accelerator: 'CmdOrCtrl+S' //快捷键：Ctrl+S
                }
            ]
        }

    ])
    Menu.setApplicationMenu(menu)

  // and load the index.html of the app.
  mainWindow.loadFile('index.html')

  // Open the DevTools.
  // mainWindow.webContents.openDevTools()

  // Emitted when the window is closed.
  mainWindow.on('closed', function () {
    // Dereference the window object, usually you would store windows
    // in an array if your app supports multi windows, this is the time
    // when you should delete the corresponding element.
    mainWindow = null
  })
}

// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
// Some APIs can only be used after this event occurs.
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {
  // On macOS it is common for applications and their menu bar
  // to stay active until the user quits explicitly with Cmd + Q
  if (process.platform !== 'darwin') app.quit()
})

app.on('activate', function () {
  // On macOS it's common to re-create a window in the app when the
  // dock icon is clicked and there are no other windows open.
  if (mainWindow === null) createWindow()
})

// In this file you can include the rest of your app's specific main process
// code. You can also put them in separate files and require them here.


ipcMain.on('ondragstart', (event, filePath) => {
  console.log(filePath)
    event.sender.startDrag({
        file: filePath,
        icon: '/path/to/icon.png'
    })
})


//读取文本文件
function readText(file){
    const fs = require('fs');
    return fs.readFileSync(file, 'utf8');
}
//保存文本内容到文件
function saveText(text, file){
    const fs = require('fs');
    fs.writeFileSync(file, text);
}

//保存当前文档
function saveCurrentDoc(){
    if(!currentFile){
        const file = remote.dialog.showSaveDialog(remote.getCurrentWindow(), {
            filters: [
                { name: "Text Files", extensions: ['txt', 'js', 'html', 'md'] },
                { name: 'All Files', extensions: ['*'] } ]
        });
        if(file) currentFile=file;
    }
    if(currentFile){
        const txtSave=txtEditor.value;
        saveText(txtSave, currentFile);
        isSaved=true;
        document.title = "Notepad - " + currentFile;
    }
}

//如果需要保存，弹出保存对话框询问用户是否保存当前文档
function askSaveIfNeed(){
    if(isSaved) return;
    const response=dialog.showMessageBox(remote.getCurrentWindow(), {
        message: 'Do you want to save the current document?',
        type: 'question',
        buttons: [ 'Yes', 'No' ]
    });
    if(response==0) saveCurrentDoc(); //点击Yes按钮后保存当前文档
}
